package executeEngine.methodInvoke.dynamicInvoke;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

class PrintLn {
    public void println(String s) {
        System.out.println("println ---- " + s);
    }
}

public class MethodHandlerDemo {

    static MethodHandle getHandler(Object receiver) {
        MethodType methodType = MethodType.methodType(void.class, String.class);
        try {
            return MethodHandles.lookup().findVirtual(receiver.getClass(), "println", methodType).bindTo(receiver);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws Throwable {
        Object obj = (System.currentTimeMillis() & 1) == 0 ? System.out : new PrintLn();
        getHandler(obj).invokeExact("Hello");
    }
}
